package lily.phs.mental;

import java.util.ArrayList;
import java.util.List;
import lily.phs.child.ImageList;
import lily.phs.database.Constants;
import lily.phs.entertain.YuleActivity;
import lily.phs.epidemic.EpidemicList;
import lily.phs.healthedu.HealthMain;
import lily.phs.object.VisitMentals;
import lily.phs.urh.PeopleScrollActivity;
import lily.phs.urh.R;
import lily.phs.urh.PeopleScrollActivity.createNewTestThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 精神病患者的详细信息以及信息管理：
 * 个人基本信息补充表；
 * 随访服务记录表（2页），记录表可新建添加
 * @author heckassitant
 *
 */
public class MentalerDetails extends Activity  implements OnClickListener,Constants{
	
	private static final String[] nameOfModuleList = {
    	"城乡居民健康档案管理","健康教育","疫情上报","卫生监督","寓教于乐"};
    private static final int[] imageOfModuleList = {
    	R.drawable.peoplehealth,R.drawable.health_education,R.drawable.yiqingshangbao,
    	R.drawable.weishengjiandu,R.drawable.entertain};
    private static final String[] mentalerTable={"重性精神疾病患者个人信息补充表","重性精神疾病患者个人随访服务记录表"};
	private MentalerInfoView mentalerInfoView;
	private VisitMentalsView_1 visitMentalsView_1;
	private VisitMentalsView_2 visitMentalsView_2;
	
	private Button btnBack,btnAdd,btnSave,btnUpdate;
	MentalScrollLayout mRoot;
	private ExpandableListView listAccount;
	private GridView gv2;
	private int profileID=0,father,call;
	private int pageIndex;
	private ProgressDialog mpDialog;
	
	public Handler mHandler = new Handler(){
    	@Override
    	public void handleMessage(Message msg) {
    		super.handleMessage(msg);
			int state = msg.what;
			if(state==1){
				pageIndex = mRoot.getCurScreen();
				switch(pageIndex){
				case 0:{
					btnAdd.setVisibility(View.GONE);
					break;
				}
				case 1:
				case 2:{
					btnAdd.setVisibility(View.VISIBLE);
					break;
				}
				}
			}
    	}
    };

	@Override
	protected void onCreate(Bundle savedInstanceState){
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.mentaler_details);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.i_title_2);
        
        btnBack = (Button)this.findViewById(R.id.title_left_btn);
        btnBack.setText("后退");
        btnBack.setOnClickListener(this);
        btnAdd = (Button)this.findViewById(R.id.title_right_btn0);
        btnAdd.setText("新建");
        btnAdd.setOnClickListener(this);
        btnAdd.setVisibility(View.GONE);
        btnSave = (Button)this.findViewById(R.id.title_right_btn);
        btnSave.setText("保存");
        btnSave.setOnClickListener(this);
        btnUpdate = (Button)this.findViewById(R.id.title_right_btn2);
        btnUpdate.setText("提交");
        btnUpdate.setOnClickListener(this);
        
        profileID = getIntent().getExtras().getInt("Profile_id");
        System.out.println("getIntent().getExtras().getInt(Profile_id);"+getIntent().getExtras().getInt("Profile_id"));
        father = getIntent().getExtras().getInt("father");
        call = getIntent().getExtras().getInt("call");
        
        mRoot = (MentalScrollLayout) findViewById(R.id.root);
        listAccount = (ExpandableListView) findViewById(R.id.listAccount);
        listAccount.setGroupIndicator(null);
        listAccount.setDivider(null);
        initList();
        initViews();

        mRoot.setToScreen(0);
        pageIndex=0;
        
        gv2 = (GridView) findViewById(R.id.gride2);
        ImageList adapter2 = new ImageList(this,imageOfModuleList,nameOfModuleList);
		gv2.setAdapter(adapter2);
		gv2.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				switch (arg2) {
				case 0:{//健康档案
					if(father==MODULE_FATHER){
						Intent editprofile = new Intent();
						Bundle bd = new Bundle();
						bd.putInt("Profile_id", profileID);//待编辑档案的ID
						bd.putInt("father", MODULE_CHILD);
						bd.putInt("call", MODULE_VACCINATION);
						editprofile.putExtras(bd);
						editprofile.setClass(MentalerDetails.this, PeopleScrollActivity.class);
						startActivity(editprofile);
						overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
					}
					else if(father==MODULE_CHILD){
						if(call==MODULE_PEOPLE_HEALTH){
							finish();
							overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
						}
						else{
							Intent editprofile = new Intent();
							Bundle bd = new Bundle();
							bd.putInt("Profile_id", profileID);//待编辑档案的ID
							bd.putInt("father", MODULE_CHILD);
							bd.putInt("call", call);
							editprofile.putExtras(bd);
							editprofile.setClass(MentalerDetails.this, PeopleScrollActivity.class);
							startActivity(editprofile);
							overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
							finish();
						}
					}
					break;
				}
				case 1:{//健康教育
					if(father==MODULE_FATHER){
						Intent editprofile = new Intent();
						Bundle bd = new Bundle();
						bd.putInt("Profile_id", profileID);//待编辑档案的ID
						bd.putInt("father", MODULE_CHILD);
						bd.putInt("call", MODULE_PEOPLE_HEALTH);
						editprofile.putExtras(bd);
						editprofile.setClass(MentalerDetails.this, HealthMain.class);
						startActivity(editprofile);
						overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
					}
					else if(father==MODULE_CHILD){
						if(call==MODULE_CHILD_MANAGEMENT){
							finish();
							overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
						}
						else{
							Intent editprofile = new Intent();
							Bundle bd = new Bundle();
							bd.putInt("Profile_id", profileID);//待编辑档案的ID
							bd.putInt("father", MODULE_CHILD);
							bd.putInt("call", call);
							editprofile.putExtras(bd);
							editprofile.setClass(MentalerDetails.this, HealthMain.class);
							startActivity(editprofile);
							overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
							finish();
						}
					}
					break;
				}
				case 2:{//疫情上报
					if(father==MODULE_FATHER){
						Intent editprofile = new Intent();
						Bundle bd = new Bundle();
						bd.putInt("Profile_id", profileID);//待编辑档案的ID
						bd.putInt("father", MODULE_CHILD);
						bd.putInt("call", MODULE_PEOPLE_HEALTH);
						editprofile.putExtras(bd);
						editprofile.setClass(MentalerDetails.this, EpidemicList.class);
						startActivity(editprofile);
						overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
					}
					else if(father==MODULE_CHILD){
						if(call==MODULE_CHILD_MANAGEMENT){
							finish();
							overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
						}
						else{
							Intent editprofile = new Intent();
							Bundle bd = new Bundle();
							bd.putInt("Profile_id", profileID);//待编辑档案的ID
							bd.putInt("father", MODULE_CHILD);
							bd.putInt("call", call);
							editprofile.putExtras(bd);
							editprofile.setClass(MentalerDetails.this, EpidemicList.class);
							startActivity(editprofile);
							overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
							finish();
						}
					}
					break;
				}
				case 3:{//卫生监督
					
					break;
				}
				case 4:{//寓教于乐
					if(father==MODULE_FATHER){
						Intent editprofile = new Intent();
						Bundle bd = new Bundle();
						bd.putInt("Profile_id", profileID);//待编辑档案的ID
						bd.putInt("father", MODULE_CHILD);
						bd.putInt("call", MODULE_PEOPLE_HEALTH);
						editprofile.putExtras(bd);
						editprofile.setClass(MentalerDetails.this, YuleActivity.class);
						startActivity(editprofile);
						overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
					}
					else if(father==MODULE_CHILD){
						if(call==MODULE_CHILD_MANAGEMENT){
							finish();
							overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
						}
						else{
							Intent editprofile = new Intent();
							Bundle bd = new Bundle();
							bd.putInt("Profile_id", profileID);//待编辑档案的ID
							bd.putInt("father", MODULE_CHILD);
							bd.putInt("call", call);
							editprofile.putExtras(bd);
							editprofile.setClass(MentalerDetails.this, YuleActivity.class);
							startActivity(editprofile);
							overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
							finish();
						}
					}
					break;
				}
					
				default:
					break;
				}
			}

		});
		
		listAccount.setOnGroupClickListener(new OnGroupClickListener(){

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// TODO Auto-generated method stub
				switch(groupPosition){
				case 0:
					mRoot.setToScreen(0);
					btnAdd.setVisibility(View.GONE);
					return true;
				case 1:
					mRoot.setToScreen(1);
					btnAdd.setVisibility(View.VISIBLE);
					return false;
				default:
						return false;
				}
			}
			
		});
		
		listAccount.setOnChildClickListener(new OnChildClickListener(){

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				btnAdd.setVisibility(View.VISIBLE);
				if(groupPosition==1){
					mRoot.setToScreen(1);
					
					visitMentalsView_1.setProfileId(profileID);
					visitMentalsView_1.setTimes((childPosition+1));
					visitMentalsView_1.fetchData();
					visitMentalsView_1.initViews();
					visitMentalsView_2.setProfileId(profileID);
					visitMentalsView_2.setTimes((childPosition+1));
					visitMentalsView_2.fetchData();
					visitMentalsView_2.initViews();
				}
				return false;
			}
			
		});
        
        mpDialog = new ProgressDialog(MentalerDetails.this);  
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
		mpDialog.setMessage("正在加载...");  
		mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
		mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
		mpDialog.show();
		new myThread(handler).start();
        
	}

	private void initViews() {
		// TODO Auto-generated method stub
		mRoot.removeAllViews();
		mentalerInfoView = new MentalerInfoView(this, profileID);
		visitMentalsView_1 = new VisitMentalsView_1(this, profileID,1);
		visitMentalsView_2 = new VisitMentalsView_2(this, profileID,1);
		
		mRoot.addView(mentalerInfoView);
		mRoot.addView(visitMentalsView_1);
		mRoot.addView(visitMentalsView_2);
	}

	private void initList() {
		// TODO Auto-generated method stub
		String[] group = new String[]{"个人信息补充表","随访服务记录表"};
		List<List<String>> children = new ArrayList<List<String>>();
		List<String> child1 = new ArrayList<String>();
		children.add(child1);
		
		final String[] PROJECTION = {VIME_PROFILEID,VIME_TIMES,VIME_DATE};
		Cursor cursor=this.managedQuery(CONTENT_URI_TB24, PROJECTION, 
				VIME_PROFILEID + "=" + profileID, null, null);

		List<String> child2 = new ArrayList<String>();
		while(cursor.moveToNext()){
			String date = cursor.getString(cursor.getColumnIndex(VIME_DATE));
			child2.add(date);
		}
		children.add(child2);
		
		MyExpandableAdapter adapter = new MyExpandableAdapter(MentalerDetails.this,
				group, children);
		listAccount.setAdapter(adapter);
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v==btnBack){
			new AlertDialog.Builder(MentalerDetails.this)
			.setIcon(R.drawable.alert_dialog_icon)
			.setTitle("您确定已经保存了要退出吗？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int whichButton) {
					MentalerDetails.this.finish();
					overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int whichButton) {

		                        /* User clicked Cancel so do some stuff */
		                   }
		                })
		                .create().show();
		}
		else if(v==btnSave){
			pageIndex = mRoot.getCurScreen();
			System.out.println("pageIndex="+pageIndex);
			int i=0;
			switch(pageIndex){
			case 0:
				mentalerInfoView.saveViews();
				 i=0;
				break;
			case 1:
				visitMentalsView_1.saveViews();
				visitMentalsView_2.saveViews();
				 i=1;
				break;
			case 2:
				visitMentalsView_1.saveViews();
				visitMentalsView_2.saveViews();
				 i=1;
				break;
			}
			Toast.makeText(this, mentalerTable[i]+"表信息保存成功!", Toast.LENGTH_SHORT).show();
		}
		else if(v==btnAdd){
			new AlertDialog.Builder(MentalerDetails.this)
			.setTitle("新建随访服务记录表")
			.setIcon(R.drawable.add_profile)
			.setMessage("保存当前信息，并且建立一张新的随访记录表，确定吗？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
             		mpDialog.setMessage("正在保存当前信息...");  
             		mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
             		mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
             		mpDialog.show();
             		//保存当前体检表的信息
             		visitMentalsView_1.saveViews();
             		visitMentalsView_2.saveViews();
    			    //新建
             		new createNewRecordThread(handler).start();	 
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			})
			.create().show();
		}
	}
	
	class createNewRecordThread extends Thread{
		private Handler handler;
		public createNewRecordThread(Handler handler){
			this.handler = handler;
		}
		
		public void run(){
			try  
	        {   
	        	Looper.getMainLooper();
	        	sleep(500); 
	        	
	        	VisitMentals vm = new VisitMentals(getBaseContext());
	        	int times = vm.getNumTimes(profileID)+1;
	        	vm.setVime_profileid(profileID);
	        	vm.setVime_times(times);
	        	vm.insertVisitMentals();
	        	
	        	visitMentalsView_1.setProfileId(profileID);
	        	visitMentalsView_1.setTimes(times);
	        	visitMentalsView_1.fetchData();
	        	visitMentalsView_2.setProfileId(profileID);
	        	visitMentalsView_2.setTimes(times);
	        	visitMentalsView_2.fetchData();
	        	
	        	Message msg = handler.obtainMessage(); 
	        	msg.what=2;
	        	handler.sendMessage(msg); 
			}  
		    catch (Exception e)  
		    {  
		        e.printStackTrace();  
		    }  
		}
	}
	
	public class myThread extends Thread{  
		private Handler handler;

		public myThread(Handler handler){
			this.handler=handler;

		}
		
		public void run(){  
	        try  
	        {   
	        	Looper.getMainLooper();
	        	sleep(1000); 
	        	
	        	mentalerInfoView.fetchData();
	        	visitMentalsView_1.findViewsById();
	        	visitMentalsView_1.fetchData();
	        	visitMentalsView_2.findViewsById();
	        	visitMentalsView_2.fetchData();
	        	
	        	Message msg = handler.obtainMessage(); 
	        	msg.what=1;
	        	handler.sendMessage(msg); 
			}  
		    catch (Exception e)  
		    {  
		        e.printStackTrace();  
		    }  
		}  
	}
	
	private final Handler handler = new Handler(Looper.getMainLooper()) {
    	public void handleMessage(Message msg) { 
    		if(msg.what==1){
    			mentalerInfoView.initViews();
    			visitMentalsView_1.setMyView();
    			visitMentalsView_1.initViews();
    			visitMentalsView_2.setMyView();
    			visitMentalsView_2.initViews();

    			mpDialog.cancel();
    		}
    		else if(msg.what==2){
    			visitMentalsView_1.initViews();
    			visitMentalsView_2.initViews();
    			
    			initList();
    			mpDialog.cancel();
    			Toast.makeText(MentalerDetails.this, "创建新随访记录表成功！", Toast.LENGTH_LONG).show();
    		}
    	} 
    }; 
    
    class MyExpandableAdapter extends BaseExpandableListAdapter{
    	
    	private Context context;
    	private String[] groupItems;
    	private List<List<String>> childItems;
    	
    	
    	public MyExpandableAdapter(Context context,String[] groupItems,
    			List<List<String>> childItems)
    	{
    		this.context = context;
    		this.groupItems = groupItems;
    		this.childItems = childItems;
    		
    	}

    	@Override
    	public Object getChild(int groupPosition, int childPosition) {
    		// TODO Auto-generated method stub
    		return null;
    	}

    	@Override
    	public long getChildId(int groupPosition, int childPosition) {
    		// TODO Auto-generated method stub
    		return childPosition;
    	}

    	/*********************************************************************/
    	@Override
    	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    		// TODO Auto-generated method stub
    		
    		LayoutInflater factory = LayoutInflater.from(context);
    		View view = factory.inflate(R.layout.panel_child_row, null);
    		
    		ChildViewHolder cHolder = new ChildViewHolder();
    		cHolder.tv_times = (TextView)view.findViewById(R.id.times);
    		cHolder.tv_date = (TextView)view.findViewById(R.id.date);
    		
    		String str = "第 " +(childPosition+1)+" 次随访服务记录表";
    		cHolder.tv_times.setText(str);
    		String str2 = childItems.get(1).get(childPosition);
    		cHolder.tv_date.setText("日期："+str2);
    		
    		return view;
    	}
    	/*********************************************************************/
    	
    	
    	@Override
    	public int getChildrenCount(int groupPosition) {
    		// TODO Auto-generated method stub
    		return this.childItems.get(groupPosition).size();
    	}

    	@Override
    	public Object getGroup(int groupPosition) {
    		// TODO Auto-generated method stub
    		return null;
    	}

    	@Override
    	public int getGroupCount() {
    		// TODO Auto-generated method stub
    		return this.groupItems.length;
    	}

    	@Override
    	public long getGroupId(int groupPosition) {
    		// TODO Auto-generated method stub
    		return groupPosition;
    	}

    	/*********************************************************************/
    	@Override
    	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    		// TODO Auto-generated method stub
    		
    		int count = getGroupCount();
    		LinearLayout view = new LinearLayout(context);
    		view.setGravity(Gravity.CENTER_VERTICAL);
    		view.setPadding(25, 0, 0, 0);
    		GroupViewHolder gHolder = new GroupViewHolder();
    		gHolder.tv_group = new TextView(context);
    		gHolder.tv_group.setText(groupItems[groupPosition]);
    		gHolder.tv_group.setTextSize(20.0f);
    		gHolder.tv_group.setTextColor(Color.BLACK);
    		
    		view.setBackgroundResource(R.drawable.exlist_father);
    		view.addView(gHolder.tv_group,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
    		return view;
    	}
    	/*********************************************************************/

    	@Override
    	public boolean hasStableIds() {
    		// TODO Auto-generated method stub
    		return true;
    	}

    	@Override
    	public boolean isChildSelectable(int groupPosition, int childPosition) {
    		// TODO Auto-generated method stub
    		return true;
    	}
    	
    	class GroupViewHolder
    	{
    		TextView tv_group;

    		GroupViewHolder()
    		{
    		}
    	}
    	
    	class ChildViewHolder
    	{
    		TextView tv_times;
    		TextView tv_date;

    		ChildViewHolder()
    		{
    		}
    	}
    }
}
